package com.xuetang.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import jakarta.servlet.http.HttpServletRequest;

/**
 * 全局错误处理控制器
 */
@Controller
public class ErrorController implements org.springframework.boot.web.servlet.error.ErrorController {

    /**
     * 处理所有错误
     */
    @RequestMapping("/error")
    public String handleError(HttpServletRequest request, Model model) {
        // 获取错误状态码
        Integer statusCode = (Integer) request.getAttribute("jakarta.servlet.error.status_code");
        String errorMessage = (String) request.getAttribute("jakarta.servlet.error.message");

        if (statusCode == null) {
            statusCode = 500;
        }

        // 设置错误信息
        model.addAttribute("status", statusCode);
        model.addAttribute("error", "请求处理失败");

        if (statusCode == 404) {
            model.addAttribute("message", "请求的页面不存在");
        } else if (statusCode == 403) {
            model.addAttribute("message", "没有访问权限");
        } else if (statusCode == 500) {
            model.addAttribute("message", "服务器内部错误");
        } else {
            model.addAttribute("message", errorMessage != null ? errorMessage : "未知错误");
        }

        // 返回错误页面
        return "error";
    }
}